package geektime.io.nio;

import java.nio.ByteBuffer;

public class ByteBufferTest {

    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(100);
        System.out.println(buffer.isDirect());
        buffer.put("hello".getBytes());
        // 通过get()方法从buffer中获取数据
        byte[] bytes = new byte[buffer.position()];
        buffer.flip();
        buffer.get(bytes);
        System.out.println(new String(bytes));
        System.out.println(buffer.remaining());
        System.out.println(new String(buffer.array()));
        buffer.flip();
        System.out.println(new String(buffer.array()));
        buffer.clear();
        System.out.println(new String(buffer.array()));
        buffer.rewind();
        System.out.println(new String(buffer.array()));
        System.out.println(buffer.remaining());

        buffer.position(2);
        ByteBuffer sliceBuffer = buffer.slice(); // 这时候sliceBuffer的position=0，limit=capacity=98
        sliceBuffer.put("hey".getBytes()); // 因为sliceBuffer和buffer共享heap bytes，所以这个时候hey是从buffer的position=2位置开始写的
        System.out.println(new String(sliceBuffer.array()));

        ByteBuffer newBuffer = sliceBuffer.duplicate();
        
        // 验证compact方法
        buffer.clear();
        buffer.put("excellent".getBytes());
        buffer.flip();
        System.out.println(new String(buffer.array()));
        buffer.get(); // 每get一次，position++一次
        buffer.get();
        buffer.get();
        ByteBuffer compact = buffer.compact();
        System.out.println(new String(compact.array()));

    }
}
